// 获取当前日期
let currentDate = new Date();
// 获取明天的日期
let tomorrow = new Date(currentDate);
tomorrow.setDate(currentDate.getDate() + 1);
// 获取后天的日期
let dayAfterTomorrow = new Date(currentDate);
dayAfterTomorrow.setDate(currentDate.getDate() + 2);
// 获取今天的年、月和日
let year = currentDate.getFullYear();
let month = currentDate.getMonth() + 1; // 月份从0开始，所以加1
let day = currentDate.getDate();
// 获取明天的年、月和日
let tyear = tomorrow.getFullYear();
let tmonth = tomorrow.getMonth() + 1; // 月份从0开始，所以加1
let tday = tomorrow.getDate();
// 获取后天的年、月和日
let dyear = dayAfterTomorrow.getFullYear();
let dmonth = dayAfterTomorrow.getMonth() + 1; // 月份从0开始，所以加1
let dday = dayAfterTomorrow.getDate();
let currentDateTime = year + "-" + (month < 10 ? "0" : "") + month + "-" + (day < 10 ? "0" : "") + day;
let tomorrowTime = tyear + "-" + (tmonth < 10 ? "0" : "") + tmonth + "-" + (tday < 10 ? "0" : "") + tday;
let dayAfterTomorrowTime =dyear + "-" + (dmonth < 10 ? "0" : "") + dmonth + "-" + (dday < 10 ? "0" : "") + dday;
//索引截取时间并去掉时间中的”07“中的“0”
let today = "今天：" + parseInt(currentDateTime.slice(5,7),10).toString()+"月"+parseInt(currentDateTime.slice(8,10),10).toString()+"日";
let tomday = "明天：" + parseInt(tomorrowTime.slice(5,7),10).toString()+"月"+parseInt(tomorrowTime.slice(8,10),10).toString()+"日";
let houday = "后天：" + parseInt(dayAfterTomorrowTime.slice(5,7),10).toString()+"月"+parseInt(dayAfterTomorrowTime.slice(8,10),10).toString()+"日";

function getUserInfo() {
    let userInfo;
    $.ajax({
        headers: {
            "token": localStorage.getItem("token")
        },
        type: 'get',
        url: serverConfig.serverUrl +'/devs/user',
        async: false,
        success: function (result) {
            userInfo = result.data;
        }
    })
    return userInfo;
}

function selectSeat(sessionId) {
    localStorage.setItem("selectSeatStatus","true")
    if (userInfo.phone == null || userInfo.realName == null) {
        layer.msg('请完善手机号和真实姓名', {icon: 2})
        return;
    }
    $.ajax({
        type: 'get',
        url: serverConfig.serverUrl +'/devs/session',
        data: {id: sessionId},
        success: function (result) {
            if (result.code == 200) {
                window.location.href = `../html/seat.html?id=${sessionId}`;
            } else if (result.code == 400) {
                layer.msg('当前场次座位已满', {icon: 2})
            }
        }
    })
}

let userInfo
$(function () {
    userInfo = getUserInfo();

    if (userInfo == null) {
        window.location.href = "../html/login.html";
    }

})


let movieid = window.location.search.substr(0);
movieid = movieid.split("=")[1];
let a;
$.ajax({
    type: 'get',
    url: serverConfig.serverUrl +`/devs/movie/findByStatus/${0}`,
    success: function (result) {
        let data = result.data;
        let str = ``;
        let count = 0;
        for (let i = 0; i < data.length; i++) {
            let img = data[i].posterImg
            let id = data[i].id
            if (id == movieid) {
                a = i;
                str += `<div onclick="change(this)" class="movie active" data-index="${count}" data-movieid="${id}">
                          <img src="../imgs/movie-img/${img}" alt="电影名称 票无忧影城">
                          </div>`
            } else {
                str += `<div onclick="change(this)" class="movie " data-index="${count}" data-movieid="${id}">
                      <img src="../imgs/movie-img/${img}" alt="电影名称 票无忧影城">
                      </div>`
            }
            count += 1
        }
        document.getElementById("y-movie").innerHTML = str
        document.getElementsByClassName('movie-name')[0].innerText = data[a].title
        document.getElementsByClassName('score sc')[0].innerText = data[a].score
        document.getElementsByClassName('value-time')[0].innerText = data[a].duration
        document.getElementsByClassName('movie-director')[0].innerText = data[a].director
        document.getElementsByClassName('text-link')[0].innerText = data[a].language
        document.getElementsByClassName('pointer')[0].style = "left:" + (71 + 170 * a) + "px";
    }
})
// 查询场次
$.ajax({
    type: 'get',
    url:serverConfig.serverUrl + `/devs/session/findMovieId`,
    data:{movieId:movieid,time:currentDateTime},
    success: function (result) {
        showSession(result);
    }
})


$(function lookTime(){
    document.getElementById("y-show-data").innerHTML = `<span>观影时间</span>
                                                                 <span class="date-item active" data-index="0" onclick="timeChange(this)" time-day="${currentDateTime}">${today}</span>
                                                                 <span class="date-item " data-index="1" onclick="timeChange(this)" time-day="${tomorrowTime}">${tomday}</span>
                                                                 <span class="date-item " data-index="2" onclick="timeChange(this)" time-day="${dayAfterTomorrowTime}">${houday}</span>`
})


function showSession(result) {
    let data = result.data;
    let str = ``
    if (data.length != 0) {
        document.getElementsByClassName("finished-all-shows")[0].style = "display:none";
        document.getElementsByClassName("plist")[0].style = "display:table";
        for (let i = 0; i < data.length; i++) {
            let starttime = data[i].starTime
            starttime = starttime.split(" ")[1];
            let endtime = data[i].endTime
            endtime = endtime.split(" ")[1]
            let language = data[i].movieLanguage
            let hall = data[i].hallType
            let price = data[i].moviePrice
            str += `<tr>
                    <td>
                        <span class="begin-time">${starttime}</span>
                        <br>
                        <span class="end-time">${endtime}</span>
                    </td>
                    <td>
                        <span class="lang">${language}</span>
                    </td>
                    <td>
                        <span class="hall">${hall}</span>
                    </td>
                    <td>
                                    <span class="sell-price">
                                        <span class="stonefont">${price}</span>
                                    </span>
                    </td>
                    <td>
                        <a onclick="selectSeat(${data[i].id})" class="buy-btn normal">选座购票</a>
                    </td>
                    </tr>`
        }
        document.getElementById("y-session-y").innerHTML = str
    } else {
        document.getElementsByClassName("finished-all-shows")[0].style = "display:block";
        document.getElementsByClassName("plist")[0].style = "display:none";
    }
}

function change(obj) {
    document.getElementsByClassName("movie active")[0].className = "movie";
    obj.className = "movie active";
    let t = obj.getAttribute('data-index');
    document.getElementsByClassName('pointer')[0].style = "left:" + (71 + 170 * t) + "px";
    $.ajax({
        type: 'get',
        url: serverConfig.serverUrl +`/devs/movie/findById/${obj.getAttribute('data-movieid')}`,
        success: function (result) {
            if (result.code == 200) {
                document.getElementsByClassName('movie-name')[0].innerText = result.data.title
                document.getElementsByClassName('score sc')[0].innerText = result.data.score
                document.getElementsByClassName('value-time')[0].innerText = result.data.duration
                document.getElementsByClassName('movie-director')[0].innerText = result.data.director
                document.getElementsByClassName('text-link')[0].innerText = result.data.language

            }
        }
    })

    $.ajax({
        type: 'get',
        url:serverConfig.serverUrl +`/devs/session/findMovieId`,
        data:{movieId:obj.getAttribute('data-movieid') , time:document.getElementsByClassName("date-item active")[0].getAttribute("time-day")},
        success:function (result){
            showSession(result);
        }
    })
}

function timeChange(obj){
    document.getElementsByClassName("date-item active")[0].className = "date-item"
    obj.className = "date-item active"
    $.ajax({
        type: 'get',
        url:serverConfig.serverUrl +`/devs/session/findMovieId`,
        data:{movieId:document.getElementsByClassName("movie active")[0].getAttribute('data-movieid'), time:document.getElementsByClassName("date-item active")[0].getAttribute("time-day")},
        success:function (result){
            showSession(result);
        }
    })
}
